<?php

namespace App\Http\Controllers;

use App\Http\Response\ApiResponse;
use Dcat\Admin\Form;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Models\Administrator;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Support\Facades\Hash;

class BaseController extends AdminController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    public function response(): ApiResponse
    {
        return new ApiResponse();
    }

    /**
     * 保存账号信息
     */
    protected function saveAdmin(Form $form){
        $id = $form->getKey();
        $model = $form->model();
        $username = $model->admin?$model->admin->username:'';
        $form->text('username','账号')->attribute(['autocomplete'=>'off'])->value($username)->required();
        $password = $form->password('password','密码')
            ->rules(['alpha_num'],['alpha_num'=>'密码必须为大小写字母或者数字'])
            ->minLength(6,'最少6位字符')
            ->maxLength(15,'最长15位字符')
            ->attribute(['autocomplete'=>'new-password']);
        if($id){
            $password->help("不修改密码,请留空");
        }else{
            $password->required();
        }
        $form->radio('status')->options(['正常','隐藏'])->default(0);
        $form->saving(function (Form $form){
            dd($form->areas);
            $name = $form->name;
            $username = $form->username;
            $password = $form->password;
            if($form->isCreating()){
                $exit = Administrator::query()->where("username",$username)->exists();
                if ($exit){
                    return $form->response()->error("此账号已存在!");
                }
                $admin = new Administrator();
                $admin->username = $username;
                $admin->name = $name;
                $admin->password = Hash::make($password);
                $res = $admin->save();
                if ($res){
                    $form->admin_id = $admin->id;
                }
            }
            if($form->isEditing()){
                $exit = Administrator::query()->where("id","<>",$form->admin_id)->where("username",$username)->exists();
                if ($exit){
                    return $form->response()->error("此账号已存在!");
                }
                $admin = Administrator::query()->where("id",$form->admin_id)->first();
                $admin->username = $username;
                $admin->name = $name;
                if ($password){
                    $admin->password = Hash::make($password);
                }
                $admin->save();
            }
            $form->deleteInput('username');
            $form->deleteInput('password');
        });
    }
}
